<?php
namespace Home\Controller;
use Think\Controller;
class SiteMapController extends BaseController {
	public function index(){
		//$this->display();
	}

	/**
	 * 生成百度最新Sitemap
	 */
	public function baidu() {
		$page = I('get.page');
		$perpage = I('get.perpage');
		$this->last('baidu', $page, $perpage);
	}

	/**
	 * 生成谷歌最新Sitemap
	 */
	public function google() {
		$page = I('get.page');
		$perpage = I('get.perpage');
		$this->last('google', $page, $perpage);
	}

	/**
	 * 生成地图文件
	 */
	public function last($target='', $page='', $perpage='50000') {
		ini_set('memory_limit','128M');
		// 保存位置
		$filename = "/{$target}{$page}.xml";
		$path = ROOT . "/SiteMap";
		$fullPath = $path . $filename;
		$url = __APP__ . "/SiteMap/{$target}{$page}.xml";

		$haveXml = file_exists($path.$filename);
		$makeTime = filemtime($path.$filename);
		$isNew = (time() - $makeTime)>21600 ? false : true; // 6个小时为新文件
		if ($haveXml and $isNew) {
			header( "HTTP/1.1 301 Moved Permanently" );
			header( "Location: {$url}" );
			//var_dump($haveXml, $makeTime, $isNew, $fullPath);
		} else { // 更新文件
			$model = D("Hash");
			$order['id'] = "desc";
			$field = 'id,hash,title,keywords,file,time';
			$list = $model->field($field)->order($order)->limit($page, $perpage)->cache(true,3600)->select();

			$this->assign("time", time());
			$this->assign("list", $list);
			echo $this->buildHtml($filename, $path, $target);
		}		
	}

	public function time() {
		echo formatTime('1377317223',"c");
	}
}